package com.ja10.books;

import com.example.books.R;

import java.io.IOException;
import java.net.MalformedURLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class BookDetailActivity extends Activity {
	
	SimpleDatabaseHelper helper = null;
	SQLiteDatabase db = null;
	private BookList book = null;
	
	String loginId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_book_detail);
		
		// 各ウィジェットの取得
		ImageView img = (ImageView)findViewById(R.id.img);
		TextView title = (TextView)findViewById(R.id.txt_title);
		TextView writer = (TextView)findViewById(R.id.txt_writer);
		TextView publisher = (TextView)findViewById(R.id.txt_publisher);
		TextView isbn = (TextView)findViewById(R.id.txt_isbn);
		TextView publicationDate = (TextView)findViewById(R.id.txt_publicationDate);
		TextView content = (TextView)findViewById(R.id.txt_content);
				
		// 各インテントを受け取る
		Intent i = this.getIntent();
		int getId = i.getIntExtra("id", 0);
		String getIsbn = i.getStringExtra("isbn");
		
		// ネットワーク接続を取得
		ConnectivityManager cm = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
		boolean net = new NetworkGet(cm).net;
		
		// ネットワークに繋がっている場合、外部DBより情報を取得
		if(net) {
			// IDが渡ってきた場合where句にIDをセット
			String where = null;
			if(getId > 0) {
				where = " and id = " + getId;
			}
			// ISBNが渡ってきた場合where句にISBNをセット
			else if(getIsbn != null) {
				where = " and isbn = '" + getIsbn + "'";
			}
			// 書籍情報を取得するSQL文の用意
			String sql = "select * from books where delete_flag = 0 and open_flag = 1" + where;

			Connection con = null;
			Statement smt = null;

			try {
				con = DBManager.getConnection();
				smt = con.createStatement();
				ResultSet rs = smt.executeQuery(sql);
				
				if(rs.first()) {
					// 書籍情報をBookListに格納
					book = new BookList();
					book.setId(rs.getInt("id"));
					book.setGenreName(rs.getInt("genre_id"));
					book.setPublisherName(rs.getInt("publisher_id"));
					book.setTitle(rs.getString("title"));
					book.setWriter(rs.getString("writer"));
					book.setContent(rs.getString("content"));
					book.setPublicationDate(rs.getString("publication_date"));
					book.setPictureBmp(rs.getString("picture"), 100);
					book.setIsbn(rs.getString("isbn"));
				} else {
					// フラグの変更等で非表示設定された場合トーストで通知
					Toast.makeText(this, "この書籍情報は現在閲覧できません", Toast.LENGTH_SHORT).show();
					finish();
				}
			} catch(SQLException e) {
				e.printStackTrace();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if(smt != null) {
					try {
						smt.close();
					} catch(SQLException ignore) {
						// none
					}
				}
				if(con != null) {
					try {
						con.close();
					} catch(SQLException ignore) {
						// none
					}
				}
			}
		}
		// ネットワークに繋がっていない場合、端末内DBより情報を取得
		else {
			// ヘルパーを準備
			helper = new SimpleDatabaseHelper(this);
			
			// 端末データベースの取得
			db = helper.getReadableDatabase();
			String[] params = {getIsbn};
			Cursor cs = db.query("myfavorites", null, "isbn = ?", params, null, null, null);
			if(cs.moveToFirst()) {
				book = new BookList();
				book.setId(cs.getInt(0));
				book.setGenreName(cs.getString(1));
				book.setPublisherName(cs.getString(2));
				book.setTitle(cs.getString(3));
				book.setWriter(cs.getString(4));
				book.setContent(cs.getString(5));
				book.setRecordDate(cs.getString(6));
				book.setPublicationDate(cs.getString(7));
				book.setPictureBmp(cs.getBlob(8));
				book.setIsbn(cs.getString(9));
			}
			cs.close();
			db.close();
			// ボタン操作の不可設定
			((Button)findViewById(R.id.btn_reserve)).setEnabled(false);
			((Button)findViewById(R.id.btn_favorite)).setEnabled(false);
		}
		
		if(book != null) {
			// 各ウィジェットにデータをセット
			title.setText(book.getTitle());
			writer.setText(book.getWriter());
			publisher.setText(book.getPublisherName());
			isbn.setText(book.getIsbn());
			if(book.getPublicationDate() != null) {
				publicationDate.setText(book.getPublicationDate().replaceAll("-", "/"));
			}
			if(book.getContent() != null || book.getContent().length() > 0) {
				content.setText(book.getContent());
			} else {
				content.setVisibility(View.GONE);
			}
			img.setImageBitmap(book.getPictureBmp());
		}

	}
	
	//----------------　[ログイン]ボタンクリック時に呼び出されるメソッド
	public void btnLogin_onClick(View view){
			
	// LoginActivityへのインテントを作成
		Intent i = new Intent(this, LoginActivity.class);
	// アクティビティを起動
		startActivity(i);
	}	
		
	// メインメニューボタン押下時の処理
	public void btn_onClick(View view){
			
		Intent i = new Intent(this, MainActivity.class);
		startActivity(i);
		finish();
	}
	
	// 予約ボタン押下時の処理
	public void reserve_onClick(View view) {
		
		SharedPreferences settings = getSharedPreferences(LoginActivity.PREFERENCES_FILE_NAME, Activity.MODE_PRIVATE);
		loginId = settings.getString("id", "");
		int state = settings.getInt("state", 0);
		
		Intent i = null;
		
		// 予約中書籍とレンタル中書籍の合計を取得
		int countSum = reserveCount() + countSearchSql(1);
		
		// ログイン時
		if(!"".equals(loginId) && state == 1) {
			// 過去に予約・貸出されている場合予約不可
			if(countSearchSql(2) > 0) {
				Toast.makeText(this, "同一書籍を複数回予約はできません", Toast.LENGTH_SHORT).show();
			}
			// 貸出と予約の合計が9冊以下の場合予約画面へ遷移
			else if(countSum < 10) {
				i = new Intent(this, ReserveEntry.class);
				finish();
			} else {
				Toast.makeText(this, "貸出と予約の合計が10冊に達しています", Toast.LENGTH_SHORT).show();
			}
		}
		// 未ログイン時
		else {
			i = new Intent(this, LoginActivity.class);
			i.putExtra("move", 1);
		}
		if(i != null) {
			i.putExtra("id", Integer.toString(book.getId()));
			startActivity(i);
		}
	}
	
	// 予約中書籍数取得
	public int reserveCount() {
		helper = new SimpleDatabaseHelper(this);
		db = helper.getReadableDatabase();
		// 予約数を取得するSQL文の用意
		String sql = "select count(*) from reserves";
		Cursor cs = db.rawQuery(sql, null);
		cs.moveToLast();
		int count = cs.getInt(0);
		cs.close();
		db.close();
		return count;
	}
		
	// レンタル中・過去予約を検索する共通処理
	public int countSearchSql(int mode) {
		
		String sql = null;
		
		switch(mode) {
			// レンタル中書籍数を取得するSQL文の用意
			case 1:
				sql = "select count(*) as cnt from members as m, rentals as r " +
						"where m.id = r.member_id and user_id = '" + loginId + "' and return_date is null";
				break;
			// 選択書籍が過去に「予約→貸出」処理が行われたかを調べるSQL文の用意
			case 2:
				sql = "select count(*) as cnt from members as m, rentals as r, books as b " +
						"where m.id = r.member_id and r.book_id = b.id " +
						"and user_id = '" + loginId + "'" +
						"and isbn = '" + book.getIsbn() + "'" +
						"and reserve_id is not null";
				break;
			default:
		}
		Connection con = null;
		Statement smt = null;
		
		int count = 0;
		
		if(sql != null) {
			try {
				con = DBManager.getConnection();
				smt = con.createStatement();
				ResultSet rs = smt.executeQuery(sql);
				
				if(rs.first()) {
					count = rs.getInt("cnt");
				}
			} catch(SQLException e) {
				e.printStackTrace();
			} finally {
				if(smt != null) {
					try {
						smt.close();
					} catch(SQLException ignore) {
						// none
					}
				}
				if(con != null) {
					try {
						con.close();
					} catch(SQLException ignore) {
						// none
					}
				}
			}
		}
		return count;
	}

	// お気に入り登録ボタン処理
	public void favorite_onClick(View view) throws SQLException {

		if(book != null) {
			new FavoriteEntry(book, this);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
